package com.corecmd.tcloud.tcimserver.im.handler;

import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;
import com.corecmd.tcloud.tcimserver.cache.ImCacheManager;
import com.corecmd.tcloud.tcimserver.im.common.ImSessionHolder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/22
 * @description :
 **/
@Slf4j
@Scope("prototype")
@Component
public class ChannelDownHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private ImCacheManager imCacheManager;
    @Value("${imserver.clientKeyPrefix}")
    private String imClientServerPrefix;
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String userName = (String) channel.attr(AttributeKey.valueOf("userName")).get();
        String userId = (String) channel.attr(AttributeKey.valueOf("userId")).get();
        log.info("客户端:"+userName+"断开连接");
        ImSessionHolder.delete(userId);
        //将客户端和服务器连接信息存入redis
        imCacheManager.deleteKey(imClientServerPrefix+userId);
        //广播下线通知
        MessageRequestPacket messageRequestPacket = new MessageRequestPacket();
        messageRequestPacket.setMsgContent("用户:"+userName+"下线了！！！");
        ImSessionHolder.broadcastMessage(messageRequestPacket,userId);
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
        log.info(cause.getMessage());
    }
}
